<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="queryParams.username" placeholder="请输入用户名称" clearable size="small" style="width: 200px" @keyup.enter.native="handleQuery" />
          </el-form-item>
          <el-form-item label="状态" prop="expire">
            <el-select v-model="queryParams.expire" placeholder="請選擇">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-form-item label="权限" prop="productId">
              <el-select v-model="queryParams.productId" placeholder="请选择开通权限">
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-form-item label="分配权限" prop="ckId">
              <el-select v-model="queryParams.ckId" placeholder="请选择分配权限">
                <el-option
                  v-for="item in productCookieList"
                  :key="item.id"
                  :label="item.code"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
<!--            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:user:add']">新增</el-button>-->
          </el-col>
          <el-col :span="1.5">
<!--            <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['system:user:edit']">修改</el-button>-->
          </el-col>
          <!--<el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:user:remove']">删除</el-button>
          </el-col>-->
          <el-col :span="1.5">
<!--            <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport" v-hasPermi="['system:user:import']">导入</el-button>-->
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['system:user:export']">导出</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column label="用户名" align="center" prop="username" :show-overflow-tooltip="true" />
          <el-table-column label="密码" align="center" prop="password" :show-overflow-tooltip="true" />
          <el-table-column show-overflow-tooltip label="cookie分配" align="center" prop="ckCode" width="200">
            <template scope="scope">
                <div v-show="!ckCodeShow || !isCurrentRow(scope)" >
                  <span @click="showCkCode(true,scope.row.line)" style="color: #0088cc;text-decoration: underline;cursor:pointer">{{scope.row.ckCode}}</span>
                </div>
                <div v-show="ckCodeShow && isCurrentRow(scope)" style="width: 70%">
                  <el-select v-model="updateCksParams.codeId" :placeholder="updateCksParams.code">
                    <el-option
                        v-for="item in productCookieList"
                        :key="item.id"
                        :label="item.code"
                        :value="item.id">
                    </el-option>
                  </el-select>
                  <el-button size="mini" type="text" @click="showCkCode(false)">取消</el-button>
                  <el-button size="mini" type="text" @click="updateCkCode(scope.row.id)">确定</el-button>
                </div>
            </template>

          </el-table-column><!--          <el-table-column label="主账户管理" align="center" prop="operateUsername" :show-overflow-tooltip="true" />-->
<!--            <el-table-column label="内置账号管理" align="center" prop="productUsers" :show-overflow-tooltip="true">-->
<!--                <template slot-scope="scope">-->
<!--                    <span style="color: #1c84c6;cursor: pointer" @click="checkProductUsers(scope.row)">{{scope.row.productUsers ? scope.row.productUsers:'-'}}</span>-->
<!--                </template>-->
<!--            </el-table-column>-->
<!--          <el-table-column label="是否激活" align="center" prop="status" width="120">-->
<!--            <template slot-scope="scope">-->
<!--              <span>{{['正常', '停用'][scope.row.status]}}</span>-->
<!--            </template>-->
<!--          </el-table-column>-->
          <el-table-column label="激活时间" align="center" prop="activeTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(new Date(scope.row.activeTime)) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="到期时间" align="center" prop="expireTime" width="160">
            <template slot-scope="scope">
              <span>{{ parseTime(new Date(scope.row.expireTime)) }}</span>
            </template>
          </el-table-column>
<!--          <el-table-column label="时长" align="center" prop="duration" width="160" />-->
          <el-table-column label="权限数量" align="center" prop="products" width="120">
            <template slot-scope="scope">
              <span style="color: #1c84c6;cursor: pointer"
                    @click="checkProductsNum(scope.row)">{{ scope.row.products }}</span>
            </template>
          </el-table-column>
          <el-table-column label="在线状态" align="center">
            <template slot-scope="scope">
              <span>{{scope.row.online ? '在线' : '离线'}}</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" align="center" prop="remark" width="160">
            <template slot-scope="scope">
              <span>{{ scope.row.remark }}</span>
            </template>
          </el-table-column>
          <el-table-column label="设置" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">编辑</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="removeUser(scope.row)">删除</el-button>
<!--              <el-button size="mini" type="text" icon="el-icon-attract" @click="removeUser(scope.row)">分配</el-button>-->
<!--              <el-button v-else size="mini" type="text" icon="el-icon-close" @click="handleStatusChange(scope.row)">激活</el-button>-->
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
      </el-col>
    </el-row>

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row>
          <el-col v-if="title !== '修改用户'" :span="24">
            <el-form-item label="创建方式">
              <el-radio-group v-model="form.operationType">
                <el-radio v-for="dict in statusOptions" :key="dict.dictValue" :label="dict.dictValue">{{dict.dictLabel}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="form.operationType === 'BATCH'" :span="24">
            <el-form-item label="创建用户个数" prop="batchUser">
              <el-input :type="form.operationType === 'BATCH' ? 'Number' : 'text'" v-model="form.batchUser" placeholder="请输入创建用户个数" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.operationType !== 'BATCH'" :span="24">
            <el-form-item label="用户名" prop="username">
              <el-input :disabled="title === '修改用户'" :type="form.operationType === 'BATCH' ? 'Number' : 'text'" v-model="form.username" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col v-if="form.operationType !== 'BATCH'" :span="24">
            <el-form-item label="密码" prop="password">
              <el-input :type="form.operationType === 'BATCH' ? 'Number' : 'text'" v-model="form.password" placeholder="请输入密码" minlength="6" />
            </el-form-item>
          </el-col>
<!--          <el-col v-if="form.operationType !== 'BATCH'"  :span="24">-->
<!--            <el-form-item label="到期时间" prop="expireTime">-->
<!--              <el-date-picker-->
<!--                v-model="form.expireTime"-->
<!--                type="date"-->
<!--                placeholder="请选择时间">-->
<!--              </el-date-picker>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
        <el-row>
          <el-col v-if="false" :span="24">
            <el-form-item label="主账户管理" prop="operateUsername">
              <el-input v-model="form.operateUsername" placeholder="请输入主账户管理" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="开通权限" prop="productIds">
              <el-select v-model="form.productIds" multiple placeholder="请选择开通权限">
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="绑定卡密">
              <el-input v-model="form.activationCode" placeholder="请输入卡密" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>



    <!--    根据权限数量查看具体权限-->
    <el-dialog
      title="包含权限"
      :visible.sync="productsDilog"
      width="600px"
      >
        <el-table
                :data="productsList"
                style="width: 100%">
            <el-table-column
                    prop="productName"
                    label="客户端名"
                    width="180">
            </el-table-column>
            <el-table-column
                    prop="clientUserExpireTime"
                    label="到期时间">
                <template slot-scope="scope">
                    <span>{{ parseTime(new Date(scope.row.clientUserExpireTime)) }}</span>
                </template>
            </el-table-column>
            <el-table-column
                    prop="clientUserDuration"
                    label="时长">
            </el-table-column>
        </el-table>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="productsDilog = false">关 闭</el-button>
  </span>
    </el-dialog>

      <!--    根据权限数量查看具体权限-->
      <el-dialog
              title="包含权限"
              :visible.sync="productUsernameDilog"
              width="600px"
      >
          <el-table
                  :data="productUsers"
                  style="width: 100%">
              <el-table-column
                      prop="productName"
                      label="产品名"
                      width="180">
              </el-table-column>
              <el-table-column
                      prop="productUsername"
                      label="内置账号名">
              </el-table-column>
          </el-table>
          <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="productUsernameDilog = false">关 闭</el-button>
  </span>
      </el-dialog>

  </div>
</template>

<script>
import {
  listUser,
  getUser,
  delUser,
  addUser,
  updateUser,
  exportUser,
  resetUserPwd,
  changeUserStatus,
  importTemplate,
  chcekProductsNum,
  chcekProductsUsers,
  removeUser
} from "@/api/system/user";
import {getCode} from "@/api/code"
import { getToken } from "@/utils/auth";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import {listData,getProducts,updateCkConfig} from "@/api/index/index"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { mapGetters } from "vuex"

export default {
  name: "User",
  components: { Treeselect },
  data() {
    return {
      options: [{
          value: undefined,
          label: '全部'
      },{
          value: '1',
          label: '过期'
      }, {
          value: '2',
          label: '未过期'
      }],
      productUsernameDilog: false,
      productUsers: [],

      productsList: [],

      productsDilog: false,

      list: [],
      //所有cookie描述
      productCookieList:[],
      //ckCode显示开关
      ckCodeShow: false,
      line: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [
        {dictValue: 'SINGLE',
          dictLabel:'单个创建'
        },
        {dictValue: 'BATCH',
          dictLabel:'批量创建'
        }
      ],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        operationType: '',
        batchUser: 'SINGLE',
        username: '',
        password: '',
        // expireTime: '',
        operateUsername: '',
        productIds: [],
        activationCode: '',
        remark:''
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        expire: undefined,
        username: undefined,
        productId: undefined,
        ckId:undefined
      },
      updateCksParams:{
        code: undefined,
        codeId: undefined,
        userId: undefined
      },
      // 表单校验
      rules: {
        operationType: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        batchUser: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        username: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
        ],
        // expireTime: [
        //   { required: true, message: "到期时间不能为空", trigger: "blur" },
        // ],
        operateUsername: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        productIds: [
          { required: true, message: "开头权限不能为空", trigger: "blur" },
        ],
        activationCode: [
          { required: true, message: "开头权限不能为空", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(['roles'])
  },

  created() {
    this.getListData()
    this.getList();
    this.getProducts();
  },
  methods: {

    handleClose() {
    },

    //根据数量查看具体权限
    checkProductsNum(row) {
      const batchId = row.batchId || row.id
      this.productsDilog = true
      chcekProductsNum(batchId).then(resp => {
        let { code, data } = resp
        if(code === 200) {
          this.productsList = data
        }
      })
    },
    //根据内置账号查看具体账号列表
    checkProductUsers(row) {
      this.productUsernameDilog = true
      this.productUsers = []
      chcekProductsUsers(row.id).then(resp => {
        let { code, data } = resp
        if(code === 200) {
          this.productUsers = data
        }
      })
    },

    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          let index = 1;
          //设置行号
            for (let user of this.userList) {
                user.line = index;
                index++;
            }
            console.log(`userList:${JSON.stringify(this.userList)}`)
          this.total = response.total;
          this.loading = false;
          this.showCkCode(false,-1);
          this.getProducts();
        }
      );
    },

    removeUser(row){
      this.$confirm(
        '确认删除?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(function () {
        return removeUser(row.id);
      }).then(() => {
        this.msgSuccess("删除成功");
        this.getList()
      })
      .catch(function () {
        this.msgError("删除失败");
      });
    },

    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status == "0" ? "冻结" : "激活";
      let status =  row.status == "0" ? "DISABLE" : "OK";
      this.$confirm(
        '确认要"' + text + '""' + row.username + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeUserStatus(row.id, status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
          this.getList()
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        operationType: '',
        batchUser: '',
        username: '',
        password: '',
        // expireTime: '',
        operateUsername: this.roles[0],
        productIds: [],
        activationCode: '',
        remark:''
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加用户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      Object.keys(this.form).map(item => {
        if(item === 'productIds') {
          this.form[item] = []
        }else {
          this.form[item] = row[item]
        }

      })
      this.checkProducts(row)
      this.open = true;
      this.title = "修改用户";
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(({ value }) => {
          resetUserPwd(row.userId, value).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("修改成功，新密码是：" + value);
            }
          });
        })
        .catch(() => {});
    },
    /** 提交按钮 */
    submitForm: function () {
      console.log(this.form,'????')
      this.$refs["form"].validate((valid) => {
        if (valid) {

          if (this.title === '修改用户') {
            updateUser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addUser(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(function () {});
    },
    /** 导出按钮操作 */
    handleExport() {
      console.log(this.ids)
      const param = {ids: this.ids.join(',')};
      this.$confirm("是否确认导出用户数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUser(param);
        })
        .then((response) => {
          this.download(response.msg);
        })
        .catch(function () {});
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    getListData() {
      listData().then(resp => {
        let {code, data} = resp
        if (code === 200) {
          this.list = data
        }
      })
    },
    getProducts(){
      getProducts().then(resp => {
          let {code,rows} = resp;
          this.productCookieList = [{
              id:-1,
              code:'无'
          }];
          if(code === 200){
              this.productCookieList = this.productCookieList.concat(rows);
          }
      })
    },
    //根据数量查看具体权限
    checkProducts(row) {
      // let parm = JSON.parse(JSON.stringify(this.form))
      this.form.id = row.id
      const batchId = row.id
      getCode(batchId).then(resp => {
        let { code, data } = resp
        if(code === 200) {
          data.forEach(item => {
            this.form.productIds.push(item.productId)
          })
        }
      })
    },
    showCkCode(bol,line){
      if(bol){
          this.getProducts();
      }
      this.ckCodeShow = bol;
      this.line = line;
    },
    isCurrentRow(scope,line){
        return (scope.$index + 1) == this.line
    },
    updateCkCode(userId){
      console.log(`item:${this.updateCksParams.codeId} userId:${userId}`)
      this.updateCksParams.userId = userId;
      updateCkConfig(this.updateCksParams).then((resp) => {
          let {code,msg,data} = resp;
          if(code === 200){
              this.msgSuccess("修改成功");
              this.showCkCode(false,-1);
              this.getList();
          }else{
              this.msgError(msg);
              this.showCkCode(false,-1);
          }
      })
    }
  },
};
</script>

<style scoped>
  ul, li {
    list-style: none;
  }

</style>
